import urllib
import json
import urllib
import urllib.request as urllib2
import sys,getopt
from data import Data,Router
class FM:
    def __init__(self,port):
        self.port = port
    def setd(self,fc,gain,sr):
        self.dev = Data()
        self.dev.fc = fc
        self.dev.gain = gain
        self.dev.sr = sr
        self.dev.module = "dev"
        self.dev.mode = "fm"
        self.dev.port = self.port
        self.view = Data()
        self.view.module = "fmv"
        self.view.port = self.port
        self.view.mode = "fm"
    
    def Req(self,req):
        print(req)
        response = urllib2.urlopen(req)
        print(response.read().decode('utf-8'))

    def newdev(self):
        h = Router("new")
        req = h.handle("dev%d"%self.port)+'?'+self.dev.urldata()
        self.Req(req)

    def startdev(self):
        h = Router("start")
        req = h.handle("dev%d"%self.port)
        self.Req(req)

    def newview(self):
        h = Router("new")
        req = h.handle("fm%d"%self.port)+'?'+self.view.urldata()
        self.Req(req)
    def afcon(self):
        h = Router("afc")
        req = h.handle("fm%d"%self.port)+'?on=true'
        self.Req(req)  

    def afcoff(self):
        h = Router("afc")
        req = h.handle("fm%d"%self.port)+'?on=false'
        self.Req(req)
    def stop(self):
        h = Router("stop")
        req = h.handle("fm%d"%self.port)
        self.Req(req)
    def start(self):
        h = Router("start")
        req = h.handle("fm%d"%self.port)
        self.Req(req)
    
def fmdevice(port,fc):
    l = FM(port)
    l.setd(fc+200e3,40.,1.92e6)
    l.newdev()
    l.startdev()
    l.newview()
    l.afcon()
def fmstart(port):
    l = FM(port)
    l.start()
def fmstop(port):
    l = FM(port)
    l.stop()

def main():
    opts, args = getopt.getopt(sys.argv[1:], "-d-s-p:-f:", ["device","stop", "port=","fc="])
    port = 0
    stop = False
    fc = 103.9e6
    device = False
    for opt_name,opt_value in opts:
        if opt_name in ('-p','--port'):
            port = int(opt_value)
        if opt_name in ('-s','--stop'):
            stop = True
        if opt_name in ('-f','--fc'):
            fc = float(opt_value)
        if opt_name in ('-d','--device'):
            device = True

    if device:
        fmdevice(port,fc)
    else:        
        if stop:
            fmstop(port)
        else:
            fmstart(port)

if __name__ == "__main__":
    main() 